import { useDispatch, useSelector } from "react-redux"
import { IconButton } from "../../components/IconButton"
import { IconDelete, IconDown, IconGift, IconLeft, IconMessage, IconPlus, IconRight, IconSearch, IconUser, IconUserAdd, IconVideoCamera, IconVoice } from "@arco-design/web-react/icon"
import { Avatar, Badge, Collapse, Divider, Dropdown, Empty, Icon, Image, Input, Menu, Message, Modal, Popover, Select, Skeleton, Tooltip, Trigger } from "@arco-design/web-react"
import { memo, useEffect, useRef, useState } from "react"

import './index.css'
import { UserInfo } from "../../domain/user"
import { FriendSearch } from "./components/search"
import http from "../../http"
import { forceRefreshFriendList, refreshFriendList, setCurrent, setType } from "../../store/features/friend"
import { updateMenusNum } from "../../store/features/menus"
import { addConversation } from "../../store/features/conversation"
import { Conversation, ConversationType } from "../../domain/im/entity"


import { setCurrent as setCurrentMenus } from "../../store/features/menus"
import { openMessage } from "../../store/features/message"
import { LeoAvatar } from "../../components/leo_Avatar"



export const Friend = () => {

    const { users, current, type } = useSelector((state: any) => {
        return state.friend.value;
    });

    const { menus } = useSelector((state: any) => {
        return state.menus.value;
    });

    const currentUserId = useSelector((state: any) => {
        return state.user.value.user.userId;
    })


    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(forceRefreshFriendList());

    }, [])


    const [friendRecord, setFriendRecord] = useState<any[]>([]);


    const fetchFriendRecordList = () => {
        const fetchData = async () => {
            const list = await http.get("/friend/record/list");
            setFriendRecord(list.data);
            dispatch(updateMenusNum({ name: "好友", num: 0 }))
        }
        fetchData();
    }


    const handlerFirendReq = async ({ state, id }: any) => {
        const response = await http.post(`/friend/handleRequest?recordId=${id}&state=${state}`);
        Message.success("操作成功");
        fetchFriendRecordList();
        dispatch(updateMenusNum({ name: "好友", num: 0 }))
        dispatch(refreshFriendList());
    }


    const menu = menus.find((item: any) => item.name == "好友");


    const getFriendRecordText = (state: any) => {
        if (state == 0 || state == 3) {
            return '已发送';
        } else if (state == 1) {
            return '已接受';
        } else if (state == 2) {
            return '已拒绝';
        } else {
            return "未知类型"
        }
    }

    useEffect(()=>{
        // console.log(users[current])
    }, [users, current])

    return <>

        <div className="flex flex-row  min-w-[1080px] ">
            <div className="w-[290px] border-r border-r-gray-200">
                <FriendSearch refreshFriendRecord={fetchFriendRecordList}></FriendSearch>

                <div className="h-[730px] overflow-y-auto pb-[20px]">
                    <div onClick={() => {
                        fetchFriendRecordList();
                        dispatch(setType(1))
                    }} className={`mt-[12px] flex flex-row justify-start items-center h-[60px] contacts cursor-pointer p-[20px] ${type == 1 ? ' bg-gray-200' : ''}`}>
                        <Badge count={menu.num ? menu.num : 0} dot dotStyle={{ width: 10, height: 10 }}>
                            <img src="/images/add_user.png" />
                        </Badge>
                        <span className="ml-3 max-w-[100px] text-ellipsis overflow-hidden text-[16px]">好友请求</span>

                    </div>


                    {
                        users && <>
                            <div className="px-[40px] "> <Divider orientation='center' >共 {users.length} 位联系人</Divider></div>
                            {
                                users && users.map((item: any, index: number) =>
                                    <div key={item.userId} onClick={() => {
                                        dispatch(setCurrent(index));
                                        dispatch(setType(0));
                                    }} className={`flex flex-row justify-start items-center cursor-pointer px-[20px] py-[10px]  ${(current == index && type == 0) ? ' bg-gray-200' : 'contacts'}`}>
                                        <LeoAvatar size={40} userPortrait={item.userPortrait} userName={item.nickName}></LeoAvatar>
                                        <span className="ml-3 max-w-[170px] text-ellipsis overflow-hidden text-[16px] text-left">{item.remark ? item.remark : item.nickName}</span>
                                    </div>)
                            }
                        </>
                    }



                </div>

            </div >
            <div className="flex-1 text-center">

                {
                    type == 1 && <>
                        <div className="w-full h-[60px] text-left flex flex-row items-center border-r border-r-gray-200">
                            <span className="ml-[25px] font-bold text-[16px]">好友申请</span>
                        </div>
                        <div className="flex-1 bg-gray-50 h-full">
                            {
                                friendRecord.length == 0 &&  <div className="pt-[100px]"><Empty /></div>
                            }
                            {
                                friendRecord.map((item) => {
                                    return <div key={item.id} className=" flex flex-row p-[24px] w-full justify-between items-center h-[60px]">
                                        {
                                            item.user && <div className="flex flex-row">
                                                {
                                                    //   <Avatar shape="square">
                                                    //      {item.user.userPortrait ? <img src={item.user.userPortrait} /> : item.user.userName}
                                                    //  </Avatar>
                                                    <LeoAvatar userPortrait={item.user.userPortrait} userName={item.user.nickName}> </LeoAvatar>
                                                }
                                                <div className="flex flex-col ml-[12px] items-start">
                                                    <div>{item.user.nickName}</div>
                                                    <div className="text-gray-400">{!item.reason ? "暂无理由" : item.reason}</div>
                                                </div>
                                            </div>
                                        }
                                        <div>
                                            <span className="ml-[25px] text-[14px]">
                                                {
                                                    item.senderId == currentUserId ? getFriendRecordText(item.state) :

                                                        item.state == 0 ? <Select
                                                            placeholder='请选择'
                                                            style={{ width: 154 }}
                                                            onChange={(value) => {
                                                                const state = value == '同意' ? 1 : (value == '拒绝' ? 2 : 3);
                                                                handlerFirendReq({ state, id: item.id })
                                                            }
                                                            }
                                                        >
                                                            {["同意", "拒绝", "忽略"].map((option, index) => (
                                                                <Select.Option key={option} value={option}>
                                                                    {option}
                                                                </Select.Option>
                                                            ))}
                                                        </Select>
                                                            : getFriendRecordText(item.state)

                                                }
                                            </span>
                                        </div>
                                    </div>
                                })
                            }
                        </div>
                    </>
                }
                {
                    users && <>
                        {
                            type == 0 && users[current] && <div className="flex flex-col items-center pt-10">
                                <div className="flex flex-row w-[60%] justify-between items-center ">
                                    <div className=" mt-[12px] flex flex-row  items-center cursor-pointer ">
                                        <LeoAvatar size={60} userPortrait={users[current].userPortrait} userName={users[current].nickName}></LeoAvatar>
                                        <div className="flex flex-col h-[60px] justify-between items-start ml-4">

                                            <span className="max-w-[160px] text-ellipsis overflow-hidden text-[16px]  text-black">{users[current].nickName}

                                                {
                                                    users[current].gender == "MALE" && <IconUser className=" ml-1 text-blue-600" />
                                                }

                                                {
                                                    users[current].gender == "FEMALE" && <IconUser className=" ml-1 text-red-400" />
                                                }
                                            </span>
                                            <span className="max-w-[160px] text-ellipsis overflow-hidden text-[16px]  text-gray-400">地区: {users[current].provinceCity}</span>
                                        </div>
                                    </div>
                                    <div className="text-[14px]  text-gray-500 flex flex-row items-center cursor-pointer">
                                        <IconDelete className="text-[20px]" />
                                        <span className="ml-1">删除好友</span>
                                    </div>
                                </div>
                                <div className="w-[60%]">
                                    <Divider></Divider>
                                </div>

                                <div className="w-[60%] flex flex-row items-center">
                                    <span className="w-[100px] text-left text-gray-400">备注</span>
                                    <div className="flex-1">
                                        <Input
                                            value={users[current].remark}
                                            defaultValue={users[current].remark}
                                            style={{ backgroundColor: 'white' }}
                                            placeholder='备注'
                                        /></div>
                                </div>
                                <div className="w-[60%]">
                                    <Divider></Divider>
                                </div>

                                <div className="w-[60%] flex flex-row items-center cursor-pointer">
                                    <span className="w-[100px] text-left text-gray-400">朋友圈</span>
                                    <div className="flex-1 flex flex-row space-x-2">
                                        <img
                                            width={40}
                                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                                            alt='lamp'
                                        />
                                        <img
                                            width={40}
                                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                                            alt='lamp'
                                        />
                                        <img
                                            width={40}
                                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                                            alt='lamp'
                                        />
                                    </div>
                                </div>

                                <div className="w-[60%]">
                                    <Divider></Divider>
                                </div>

                                <div className="w-[60%] flex flex-row items-start ">
                                    <span className="w-[100px] text-left text-gray-400">个性签名</span>
                                    <div className="flex-1 text-left ">
                                        {users[current].signature ?? ""}
                                    </div>
                                </div>

                                <div className="w-[60%]">
                                    <Divider></Divider>
                                </div>

                                <div className="flex flex-row w-[40%] justify-between mt-7">
                                    <div className="flex flex-col items-center cursor-pointer" onClick={() => {

                                        const conversation: Conversation = {
                                            type: ConversationType.private,
                                            lastMessage: null,
                                            targetId: users[current].userId,
                                            userName: users[current].userName,
                                            portrait: users[current].userPortrait
                                        };


                                        const fetchMessage = async () => {
                                            const respones = await http.get("/message/list?targetId=" + users[current].userId)
                                            dispatch(openMessage({ messages: respones.data, targetId: users[current].userId }));
                                        }

                                        fetchMessage();

                                        dispatch(addConversation(conversation));
                                        dispatch(setCurrentMenus(0))

                                    }}>
                                        <IconMessage className="text-[30px] text-[#333]"></IconMessage>
                                        <span className="text-[12px] mt-1 text-gray-500">发消息</span>
                                    </div>

                                    <div className="flex flex-col items-center cursor-pointer">
                                        <IconVoice type="icon-yuyin" className="text-[30px] text-[#333]"></IconVoice>

                                        <span className="text-[12px] mt-1 text-gray-500">语音通话</span>
                                    </div>

                                    <div className="flex flex-col items-center cursor-pointer">
                                        <IconVideoCamera className="text-[30px] text-[#333]"></IconVideoCamera>
                                        <span className="text-[12px] mt-1 text-gray-500">视频通话</span>
                                    </div>

                                </div>
                            </div>
                        }

                    </>
                }
            </div>
        </div >

    </>
}


